import { on, off } from "/@/utils/dom";
export interface ResizeTask {
  id: number;
  resize: () => void;
}
interface ResizeOptions {
  immediate?: boolean;
  isDebounce?: boolean;
}

const tasks: ResizeTask[] = [];
const handler = function () {
  tasks.forEach((task) => {
    task.resize();
  });
};

let debounceInter: NodeJS.Timeout | null = null;
const debounceWait = 200;
const debounceTasks: ResizeTask[] = [];
function debounceHandler() {
  if (debounceInter) {
    clearTimeout(debounceInter);
  }
  debounceInter = setTimeout(() => {
    debounceTasks.forEach((task) => {
      task.resize();
    });
  }, debounceWait);
}
let id = 0;
export default {
  add(fn: () => void, options?: ResizeOptions) {
    id++;
    const _tasks = options?.isDebounce ? debounceTasks : tasks;
    if (_tasks.length === 0) {
      on(window, "resize", options?.isDebounce ? debounceHandler : handler);
    }
    _tasks.push({
      id,
      resize: fn,
    });
    if (options?.immediate) {
      fn();
    }
    // console.log("resizer add", _tasks.length);
    return id;
  },
  remove(id: number, options?: ResizeOptions) {
    const _tasks = options?.isDebounce ? debounceTasks : tasks;
    _tasks.forEach((task, i) => {
      if (task.id === id) {
        _tasks.splice(i, 1);
        return false;
      }
    });
    // console.log("resizer remove", _tasks.length);
    if (_tasks.length === 0) {
      off(window, "resize", options?.isDebounce ? debounceHandler : handler);
    }
  },
};
